package org.example;
import product.Movie;
import product.SaleRecord;
import product.Seat;
import product.Show;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

public class ReceptionService {
    private User currentReception;
    private ManagerService managerService;
    private Scanner scanner = new Scanner(System.in);
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    private Date saleTime;

    public ReceptionService(ManagerService managerService) {
        this.managerService = managerService;
    }

    // 前台主菜单
    public void showReceptionMenu() {
        while (isLoggedIn()) {
            System.out.println("\n=== 前台菜单 ===");
            System.out.println("1.退出 2.列出影片 3.列出场次 4.座位信息 5.售票 6.退票");
            System.out.print("选择：");
            try {
                int choice = Integer.parseInt(scanner.nextLine());
                switch (choice) {
                    case 1:
                        logout();
                        break;
                    case 2:
                        listMovies();
                        break;
                    case 3:
                        listShows();
                        break;
                    case 4:
                        showSeats();
                        break;
                    case 5:
                        sellTicket();
                        break;
                    case 6:
                        refundTicket();
                        break;
                    default:
                        System.out.println("无效选择（1-6）");
                }
            } catch (NumberFormatException e) {
                System.out.println("请输入数字");
            }
        }
    }

    // 列出影片
    private void listMovies() {
        System.out.println("\n=== 影片列表 ===");
        List<Movie> movies = managerService.getMovies();
        if (movies.isEmpty()) {
            System.out.println("暂无影片信息");
            return;
        }
        for (Movie movie : movies) {
            movie.displayInfo();
            System.out.println("---------------------");
        }
    }

    // 列出场次信息
    private void listShows() {
        System.out.println("1.近一周 2.当日 3.近3日");
        System.out.print("选择：");
        try {
            int choice = Integer.parseInt(scanner.nextLine());
            if (choice < 1 || choice > 3) {
                System.out.println("无效选择（1-3）");
                return;
            }

            Show[] showsArr = managerService.getShows();
            List<Show> shows = new ArrayList<>();
            for (Show show : showsArr) {
                shows.add(show);
            }

            if (shows.isEmpty()) {
                System.out.println("暂无场次信息");
                return;
            }

            // 筛选时间范围
            Date now = new Date();
            Date start = now;
            Date end = new Date(now.getTime() + TimeUnit.DAYS.toMillis(7));

            if (choice == 2) { // 当日
                Calendar cal = Calendar.getInstance();
                cal.setTime(now);
                cal.set(Calendar.HOUR_OF_DAY, 0);
                cal.set(Calendar.MINUTE, 0);
                cal.set(Calendar.SECOND, 0);
                start = cal.getTime();

                cal.set(Calendar.HOUR_OF_DAY, 23);
                cal.set(Calendar.MINUTE, 59);
                cal.set(Calendar.SECOND, 59);
                end = cal.getTime();
            } else if (choice == 3) { // 近3日
                end = new Date(now.getTime() + TimeUnit.DAYS.toMillis(3));
            }

            // 过滤并显示
            System.out.println("筛选后的场次信息：");
            boolean hasShow = false;
            for (Show show : shows) {
                if (show.getTime().after(start) && show.getTime().before(end)) {
                    hasShow = true;
                    System.out.printf("场次ID：%d，影片：%s，放映厅：%s，时间：%s，票价：%.2f元\n",
                            show.getId(),
                            show.getMovie().getName(),
                            show.getHall(),
                            sdf.format(show.getTime()),
                            show.getPrice());
                }
            }
            if (!hasShow) {
                System.out.println("该时间范围内无场次");
            }
        } catch (NumberFormatException e) {
            System.out.println("请输入有效的数字");
        }
    }

    // 显示座位信息
    private void showSeats() {
        try {
            System.out.print("请输入场次ID：");
            int id = Integer.parseInt(scanner.nextLine().trim());
            Show show = findShowById(id);

            if (show == null) {
                System.out.println("场次不存在");
                return;
            }

            System.out.println("\n=== 座位信息 ===");
            System.out.printf("影片：%s，场次：%s %s\n",
                    show.getMovie().getName(),
                    show.getHall(),
                    sdf.format(show.getTime()));
            show.displaySeats();
            System.out.println("(O=可选，X=已售)");
        } catch (NumberFormatException e) {
            System.out.println("场次ID格式错误");
        }
    }

    // 售票功能
    private void sellTicket() {
        try {
            System.out.print("场次ID：");
            int id = Integer.parseInt(scanner.nextLine().trim());
            Show show = findShowById(id);

            if (show == null) {
                System.out.println("场次不存在");
                return;
            }

            // 显示当前场次信息
            System.out.printf("当前场次：%s（%s %s），票价：%.2f元\n",
                    show.getMovie().getName(),
                    show.getHall(),
                    sdf.format(show.getTime()),
                    show.getPrice());

            // 显示可选座位
            System.out.println("可选座位（O表示可选，X表示已售）：");
            show.displaySeats();

            // 选座逻辑
            System.out.print("请输入要购买的座位（格式：行号,列号，多个用逗号分隔，如1,1,2,3）：");
            String seatInput = scanner.nextLine().trim();
            String[] seats = seatInput.split(",");

            if (seats.length % 2 != 0) {
                System.out.println("座位格式错误，请按行号,列号格式输入");
                return;
            }

            Set<Seat> selectedSeats = new HashSet<>();
            for (int i = 0; i < seats.length; i += 2) {
                try {
                    int row = Integer.parseInt(seats[i].trim());
                    int col = Integer.parseInt(seats[i + 1].trim());
                    Seat seat = new Seat(row, col);

                    // 检查座位是否存在且可用
                    if (!show.checkSeatAvailability(row, col)) {
                        System.out.println("座位" + row + "," + col + "不可用（已售或不存在）");
                        return;
                    }
                    selectedSeats.add(seat);
                } catch (NumberFormatException e) {
                    System.out.println("座位格式错误，包含非数字字符");
                    return;
                }
            }

            // 占用座位
            show.occupySeats(selectedSeats);

            // 创建售票记录
            for (Seat seat : selectedSeats) {
                String ticketId = "null";
                SaleRecord record = new SaleRecord(ticketId, show, seat, show.getPrice(), saleTime);
                managerService.addSaleRecord(record);
                System.out.printf("售票成功！电子票号：%s，座位：%d行%d列\n",
                        record.getTicketId(), seat.getRow(), seat.getCol());
            }

        } catch (NumberFormatException e) {
            System.out.println("场次ID格式错误");
        }
    }

    // 退票功能
    private void refundTicket() {
        System.out.print("电子票号：");
        String ticketId = scanner.nextLine().trim();

        if (ticketId.isEmpty()) {
            System.out.println("电子票号不能为空");
            return;
        }

        // 查找售票记录
        SaleRecord targetRecord = null;
        List<SaleRecord> records = managerService.getSaleRecords();
        for (SaleRecord record : records) {
            if (record.getTicketId().equals(ticketId)) {
                targetRecord = record;
                break;
            }
        }

        if (targetRecord == null) {
            System.out.println("未找到该电子票记录");
            return;
        }

        // 检查是否已退票
        if (targetRecord.isRefunded()) {
            System.out.println("该票已退票，无法重复退票");
            return;
        }

        // 检查退票时间（需在放映前30分钟以上）
        Show show = targetRecord.getShow();
        Date now = new Date();
        long timeDiff = show.getTime().getTime() - now.getTime();
        if (timeDiff < 30 * 60 * 1000) { // 30分钟（毫秒）
            System.out.println("距离放映时间不足30分钟，无法退票");
            return;
        }

        // 执行退票
        targetRecord.setRefunded(true);
        targetRecord.setRefundTime(new Date());
        targetRecord.setRefundAmount(targetRecord.getPrice());
        show.releaseSeat(targetRecord.getSeat());
        System.out.printf("退票成功！票号：%s，退款金额：%.2f元\n",
                ticketId, targetRecord.getPrice());
    }

    // 根据ID查找场次
    private Show findShowById(int id) {
        Show[] shows = managerService.getShows();
        for (Show show : shows) {
            if (show.getId() == id) {
                return show;
            }
        }
        return null;
    }

    // 退出登录
    private void logout() {
        currentReception = null;
        System.out.println("已退出登录");
    }

    // 检查是否登录
    private boolean isLoggedIn() {
        return currentReception != null;
    }

    // 设置当前登录前台
    public void setCurrentReception(User loginUser) {
        this.currentReception = loginUser;
    }
}